package com.twang.stock.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.twang.stock.Entity.ShiShiData;
import com.twang.stock.common.DateUtil;
import com.twang.stock.common.http.HtmlTools;
import com.twang.stock.email.SendmailService;
import com.twang.stock.entity.*;
import com.twang.stock.entity.ex.CompanyStockMinutesEx;
import com.twang.stock.mapper.*;
import com.twang.stock.service.jinyan.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WeiPanJianQianService {

    @Resource
    private CompanyCodeInfoMapper companyCodeInfoMapper;


    @Resource
    private StockHotInfoMapper stockHotInfoMapper;

    @Autowired
    private MinutesChengJIaoeService minutesChengJIaoeService;


    @Resource
    private UserMapper userMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private SendmailService sendmailService;

    public void execute(String key) throws InterruptedException {
        //查询列表
        List<CompanyCodeInfo> companyCodeInfoList = companyCodeInfoMapper.queryMarketValueMore100Y();
        //初始化参数
        List<CompanyStockMinutesEx> companyStockMinutesExes=executeGetNowData(companyCodeInfoList);
        //过滤组合
        List<CompanyStockMinutesEx> list= getZhangTingDESC(companyStockMinutesExes,companyCodeInfoList);
        //执行预警
        warnHitDatas(list,key);
    }

    /**
     * 获取data
     * @return
     * @throws InterruptedException
     */
    public List<CompanyStockMinutesEx> executeGetNowData( List<CompanyCodeInfo> companyCodeInfoList) throws InterruptedException {
        List<CompanyStockMinutesEx> companyStockMinutesList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(companyCodeInfoList)) {
            List<List<CompanyCodeInfo>> partionList = Lists.partition(companyCodeInfoList, companyCodeInfoList.size() / 200);
            for (List<CompanyCodeInfo> _list : partionList) {
                List<String> companyName = _list.stream().map(CompanyCodeInfo::getCompanyCode).collect(Collectors.toList());
                List<ShiShiData> shiShiDataList = HtmlTools.getGpdatas(companyName);
                if (org.apache.commons.collections.CollectionUtils.isEmpty(shiShiDataList)) {
                    return null;
                }
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(shiShiDataList)) {
                    shiShiDataList.stream().forEach(shiShiData -> {
                        CompanyStockMinutesEx companyStockMinutes = new CompanyStockMinutesEx();
                        companyStockMinutes.setDate(DateUtil.getToday().substring(0, 8));
                        //companyStockMinutes.setMinutes(HolidayCopy.getHHmmss().substring(8, 12));
                        companyStockMinutes.setCompanyCode(shiShiData.getCode());
                        companyStockMinutes.setCompanyName(shiShiData.getGpname());
                        if (shiShiData.getGptime().startsWith("15") || shiShiData.getGptime().startsWith("16") || shiShiData.getGptime().startsWith("17")) {
                            shiShiData.setGptime("1500");
                        }
                        companyStockMinutes.setMinutes(shiShiData.getGptime());
                        companyStockMinutes.setDate(shiShiData.getGpdate());
                        //排除该时段的计算
                        companyStockMinutes.setPrice(new BigDecimal(shiShiData.getPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                        companyStockMinutes.setTradeSum(new BigDecimal(shiShiData.getAmount()).setScale(2, BigDecimal.ROUND_HALF_UP));
                        companyStockMinutes.setTradeVol(new BigDecimal(shiShiData.getSumvol()).setScale(2, BigDecimal.ROUND_HALF_UP));
                        companyStockMinutes.setZhangDie(shiShiData.getZhangdie());
                        companyStockMinutes.setCreateTime(new Date());
                        companyStockMinutesList.add(companyStockMinutes);
                    });
                }
            }
        }
        return companyStockMinutesList;

    }

    /**
     * 查询涨停原因
     * @param todayVolumeExceedingBillion
     * @param companyCodeInfos
     */
    public  List<CompanyStockMinutesEx>  getZhangTingDESC(List<CompanyStockMinutesEx> todayVolumeExceedingBillion,List<CompanyCodeInfo> companyCodeInfos){
        List<CompanyStockMinutesEx> stockMinutes=Lists.newArrayList();
        if (!org.springframework.util.CollectionUtils.isEmpty(todayVolumeExceedingBillion)) {
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            todayVolumeExceedingBillion.stream().forEach(item -> {
                CompanyCodeInfo targetInfo = companyCodeInfos.stream().filter(info -> info.getCompanyCode().equals(item.getCompanyCode())).findFirst().orElse(null);
                item.setCompanyCode(item.getCompanyCode().substring(2, 8));
                if (null != targetInfo && null == stringObjectHashMap.get(item.getCompanyCode())) {
                    //判断市值大于300亿的，涨幅大于5%的
                    if (targetInfo.getMarketValue().compareTo(new BigDecimal(200)) == 1 && item.getZhangDie().compareTo(new BigDecimal(5)) >= 0) {
                        item.setMarketCapitalization(targetInfo.getMarketValue());
                        //获取板块
                        minutesChengJIaoeService.getBanKuaiAndZhangTingReason(item);
                        stockMinutes.add(item);
                        stringObjectHashMap.put(item.getCompanyCode(), item);
                    } else if (targetInfo.getMarketValue().compareTo(new BigDecimal(100)) == 1 && item.getZhangDie().compareTo(new BigDecimal(7)) >= 0) {
                        item.setMarketCapitalization(targetInfo.getMarketValue());
                        //今天的市值大于100亿，并且涨幅超过7的
                        minutesChengJIaoeService.getBanKuaiAndZhangTingReason(item);
                        stockMinutes.add(item);
                        stringObjectHashMap.put(item.getCompanyCode(), item);
                    }
                }

            });
        }
        return stockMinutes;
    }

    /**
     * 预警数据
     */
    public void warnHitDatas(List<CompanyStockMinutesEx> obj,String key){
        List<StockHotInfo> stockHotInfos = stockHotInfoMapper.selectListOrderByDateDESC();
        obj.stream().forEach(item -> {
            List<String> hitDates = org.assertj.core.util.Lists.newArrayList();
            //往前推2天，如果出现3天两榜，就值的预警
            for (int i = 0; i <= 2; i++) {
                //上一个
                if (stockHotInfos.get(i).getInfo().contains(item.getCompanyName())) {
                    hitDates.add(stockHotInfos.get(i).getDate());
                }
            }
            //如果有命中 直接更新
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(hitDates)) {
                item.setHitDates(hitDates);
                //执行预警
                String message = String.format("【%s】在【%s】被命中，请注意观察，盘中提示，不会预警, 原因：%s", item.getCompanyName(), hitDates,item.getZtDesc());
                //预警
                if ("TEST".equals(key)) {
                    //开始预警
                    User user = userMapper.selectByPrimaryKey(1);
                    if (null != user) {
                        log.info(">>>>>>>>>>>> start 命中预警 user id ={} email={}  message={}", 1, user.getEmail(),message);
                        sendmailService.sendMailWithEmail(message, item.getCompanyName(), item.getCompanyName(), user.getId());
                    }
                } else {
                    List<String> ids = Arrays.asList(commonService.getValue("warn_da_pan_wen_du").toString().split(","));
                    for (String id : ids) {
                        //开始预警
                        User user = userMapper.selectByPrimaryKey(id);
                        if (null != user) {
                            log.info(">>>>>>>>>>>> start 命中预警 user id ={} email={} ", id, user.getEmail());
                            sendmailService.sendMailWithEmail(message, item.getCompanyName(), item.getCompanyName(), user.getId());
                        }
                    }
                }
            }
        });
    }

}
